package com.feicheng.common.config;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.excel.util.StringUtils;
import com.feicheng.common.token.Token;
import com.feicheng.common.token.TokenContainer;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TokenFilter implements Filter {

    @Autowired
    TokenContainer tokenContainer;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletResponse res = (HttpServletResponse) response;
        HttpServletRequest req = (HttpServletRequest) request;

        String TOKENID = req.getHeader("TOKEN");
        
        if (StringUtils.hasLength(TOKENID)) {
        	Token token = tokenContainer.getToken(TOKENID);
        	
        	if (null == token) {
        		token = tokenContainer.newToken();
        		TOKENID = token.getTokenId();
        		res.setHeader("Access-Control-Expose-Headers", "TOKEN");
            	res.setHeader("TOKEN", token.getTokenId());
            	log.debug("token过期，初始化token:"+TOKENID);
        	} else {
        		if ((TokenContainer.currentMin() - token.getMinute()) > TokenContainer.TG) {
            		tokenContainer.removeToken(TOKENID);
            		token = tokenContainer.newToken();
            		TOKENID = token.getTokenId();
            		res.setHeader("Access-Control-Expose-Headers", "TOKEN");
                	res.setHeader("TOKEN", token.getTokenId());
                	log.debug("token超时，初始化token:"+TOKENID);
                }
        	}
        	
        } else {
        	Token token = tokenContainer.newToken();
        	TOKENID = token.getTokenId();
        	res.setHeader("Access-Control-Expose-Headers", "TOKEN");
        	res.setHeader("TOKEN", token.getTokenId());
        	log.debug("初次访问，初始化token:"+TOKENID);
        }
        
        TokenContainer.setCurrentTokenId(TOKENID);
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
}
